<template>
  <div>
    <div class="head">
      <div class="scale_box">
        <div class="scale_title">
          <p>保险状态：{{switchStatus == 2?'正常':'停用'}}</p>
          <div>
            <el-button type="primary" @click="switchChange">{{switchStatus == 2?'停用保险':'启用保险'}}</el-button>
            <el-button type="primary" @click="addReview">新增保险审核</el-button>
            <el-button type="primary" @click="recordsVisible = true">变更记录</el-button>
          </div>
        </div>
        <el-table :data="insuranceTableData" stripe border>
          <el-table-column label="保单状态" align="center" prop="policyStatusDict" :show-overflow-tooltip="true" />
          <el-table-column label="保险类型" align="center" prop="insType" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="insTypeList" :value="scope.row.insType" />
            </template>
          </el-table-column>
          <el-table-column label="保额（元）" align="center" prop="changeTotal" :show-overflow-tooltip="true" />
          <el-table-column label="保险开始时间" align="center" prop="changeStartTime" :show-overflow-tooltip="true" />
          <el-table-column label="保险结束时间" align="center" prop="changeEndTime" :show-overflow-tooltip="true" />
          <el-table-column label="保险可划付比例" align="center" prop="insRemitRatio" :show-overflow-tooltip="true" >
            <template slot-scope="scope">
                <p>{{scope.row.insRemitRatio?Number(scope.row.insRemitRatio) + '%':'-'}}</p>
            </template>
          </el-table-column>
          <el-table-column label="每月最高可提现比例" align="center" prop="insApplyRemitRatio" :show-overflow-tooltip="true" >
            <template slot-scope="scope">
                <p>{{scope.row.insApplyRemitRatio?Number(scope.row.insApplyRemitRatio) + '%':'-'}}</p>
            </template>
          </el-table-column>
          <el-table-column label="保险合约" align="center" prop="insuranceContract" :show-overflow-tooltip="true" >
              <template slot-scope="scope">
                <el-link v-if="scope.row.insuranceContract !=''" :href="scope.row.insuranceContract" target="_blank">合约.pdf</el-link>
                <p v-else>-</p>
              </template>
          </el-table-column>
        </el-table>

      </div>
    </div>
    <div class="head">
      <div class="scale_box">
        <div class="scale_title">参保预付卡列表</div>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="卡类型：">
            <el-select v-model="formInline.cardType" placeholder="全部">
              <el-option v-for="item in cardTypeList" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发售状态：">
            <el-select v-model="formInline.status" placeholder="全部">
              <el-option v-for="item in billTypeList" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="卡名称：">
            <el-input v-model="formInline.name" placeholder="请输入卡名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="reset">重置</el-button>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
        </el-form>
        <div class="listBox">
          <div class="listBox_head">
            <!-- <export-excel-button title="账单列表" action="/bg/merchant/data/CardBillList/export" :params="ExportParams" /> -->
            <el-button type="primary" @click="addSumit">新增</el-button>
          </div>
          <ex-table ref="table" :loading="loading" :table-column="tableColumn" :table-data="tableData"
            @pageSizeChange="handleSizeChange" @currentPageChange="handleCurrentChange">
            <template v-slot:validityTypeDict="{ scope }">
              <div v-if="scope.row.cardType == 9">{{ scope.row.usableCount }}天</div>
              <div v-else>{{ scope.row.validityTypeDict }}</div>
            </template>
            <template v-slot:operate="{ scope }">
              <el-button @click="remove(scope.row.id)" size="mini" type="danger">移除</el-button>
            </template>
          </ex-table>
        </div>
      </div>
    </div>
    <!-- 新增 -->
    <detail-dialog v-if="dialogVisible" :id="id" :visible.sync="dialogVisible" @success="_handleSuccess" />
    <!-- 变更记录 -->
    <change-records v-if="recordsVisible" :id="id" :visible.sync="recordsVisible" />
    <!--新增保险审核 -->
    <insuranceReview v-if="isInsuranceReview" :id="id" :insuranceWalletId="insuranceWalletId" :visible.sync="isInsuranceReview" @success="_handleSuccess"></insuranceReview>
  </div>
</template>
<script>
import {
  mapState
} from "vuex";
import {
  newInsuranceDetail,
  insuranceStatus,
  insuranceCardList,
  removeInsurance,
  walletDetail
} from "@/api/merchants";
import handlePageMixin from "@/mixins/handlePageMixin";
import ExportExcelButton from "@/components/ExportExcelButton/index";
import InsuranceReview from "./insuranceSettings/insuranceReview";
import DetailDialog from './insuranceSettings/DetailDialog';
import changeRecords from './insuranceSettings/changeRecords'
export default {
  name: "insuranceSettings",
  components: {
    ExportExcelButton,
    DetailDialog,
    changeRecords,
    InsuranceReview
  },
  mixins: [handlePageMixin],
  computed: {
    ...mapState({
      cardTypeList: function (state) {
        return state.common["asset_card_type"]; // 要取this的实例，只能用不同函数，不能用箭头函数
      }
    }),
    ExportParams() {
      const {
        id: ticketId
      } = this;
      const params = {
        ...this.pageOptions,
      };
      return params;
    },
  },
  data() {

    return {
      action: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile",
      fileList: [],
      fileName: '', //上传文件名称
      loading: false,
      isInsuranceReview:false,//新增保险状态
      switchStatus: 2, //保险开关状态
      delivery: 1,
      insuranceTableData:[],//保险列表
      insTypeList:[],//保险类型
      ruleForm: {
        merchantId: '', //商家id
        startTime: '', //保险期限开始时间 yyyy-MM-dd
        endTime: '', //保险期限结束时间 yyyy-MM-dd
        total: '', //保额设置
        insuranceContract: '', //保险合约
        insApplyRemitRatio: '',//商户每月可申请划付比例（申请划付使用） 单位百分比	
        insRemitRatio: '',//保险可划付比例（申请划付使用）单位百分比
        insType: '',//保险类型 1 自动划付 2 申请划付 merchant_ins_type
      },
      dialogVisible: false, //弹窗
      recordsVisible: false,//变更记录弹窗
      id: "",//
      insuranceWalletId:'',//保险详情id
      formInline: {
        merchantId: "", //商家id
        cardType: "", //卡类型 asset_card_type
        name: "", //卡名称
        status: "", //发售状态 asset_status
      },
      billTypeList: [],
      tableData: [],
      tableDataTwo: [],
      tableColumn: [{
        prop: "cardTypeDict",
        label: "卡类型",
        width: 120
      },
      {
        prop: "name",
        label: "卡名称",
      },
      {
        prop: "statusDict",
        label: "发售状态",
        width: 120
      },
      {
        prop: "createTime",
        label: "发卡时间"
      },
      {
        prop: "validityTypeDict",
        slot: true,
        slotName: "validityTypeDict",
        label: "有效期",
        width: 140
      },
      {
        prop: "issueTotal",
        label: "计划发售量"
      },
      {
        prop: "buyMoney",
        label: "发售金额（￥）/张"
      },
      {
        prop: "used",
        label: "已发售卡/张",
        width: 120
      },
      {
        label: "操作",
        slot: true,
        slotName: "operate",
        fixed: "right",
      },
      ],
    };
  },
  created() {
    let query = this.$route.query;
    this.id = query.id;
    // this.getApi()
  },
  methods: {
    getApi() {
      this.getSelectListFunc()
      this.getNewInsuranceDetail()
      this.getWalletDetail()
      this.getList();
    },
    getSelectListFunc() {
      var dictType = "asset_status,merchant_ins_type";
      this.$getSelectList(dictType)
        .then(res => {
          var arr = [{
          id: "",
          value: "全部",
        },];
          this.billTypeList = arr.concat(res.result[0].dictList); //获取卡状态
          this.insTypeList = res.result[1].dictList;
        })
        .finally(() => {
          
        });
    },
    // 查询保险钱包信息
    getWalletDetail(){
      walletDetail(this.id).then((res) => {
         var data = res.result
         this.insuranceWalletId = data.insuranceWalletId
         this.switchStatus = data.insuranceStatus && data.insuranceStatus !=''?data.insuranceStatus:2

      });
    },
    getNewInsuranceDetail() { //获取查询商家保险配置
      newInsuranceDetail(this.id).then((res) => {
         var data = res.result
         if(data){
            this.insuranceTableData = []
            this.insuranceTableData.push(data)
         }
      });
    },
    // 新增保险审核
    addReview() {
      this.isInsuranceReview = true
    },
    switchChange(e) { //保险规则配置开关
      // status 1关  2开
      if (this.insuranceTableData && this.insuranceTableData.length > 0) {
        let params = {
              id: this.insuranceWalletId,
              status: this.switchStatus == 2 ? 1:2
          }
          insuranceStatus(params).then((res) => {
            this.$message.success('操作成功');
            this.getNewInsuranceDetail()
            this.getWalletDetail()
          })
      }else{
        this.$message.error('未设置保险配置无法开启');
        this.switchStatus = 2
      }

    },

    remove(id) { //移除
      this.$confirm('是否移除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeInsurance(id).then((res) => {
          this.$message.success('操作成功');
          this.reset()
        });
      }).catch(() => {

      });
      // removeInsurance(id).then((res) => {
      //   this.$message.success('操作成功');
      // });
    },
    addSumit() { //新增
      // this.getmerchantCardList();
      this.dialogVisible = true
    },
    _handleSuccess() {
      this.getNewInsuranceDetail()
      this.getWalletDetail()
      this.reset()
    },
    onSubmit() {
      //查询
      this.pageOptions.pageNum = 1
      this.$refs.table.pageOptions.pageNum = 1
      this.getList();
    },
    reset() {
      this.formInline = {}
      this.pageOptions.pageNum = 1
      this.$refs.table.pageOptions.pageNum = 1
      this.getList();
    },
    getList() { //查询参保预付卡列表
      this.formInline.merchantId = this.id
      const params = {
        ...this.pageOptions,
        ...this.formInline,
      };
      this.loading = true;
      insuranceCardList(params)
        .then((res) => {
          this.tableData = res.result.records;
          this.$refs.table.pageOptions.total = res.result.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};

</script>
<style scoped>
.head {
  display: flex;
  align-items: center;
  box-shadow: 0px 4px 12px 0px rgba(1, 41, 99, 0.06);
  border-radius: 8px;
  background-color: #ffffff;
  padding: 20px;
  margin-bottom: 20px;
}

.scale_box {
  padding: 0;
  width: 100%;
  color: #333;
  font-size: 15px;
}

.scale_title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 25px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.button_box {
  margin: 40px 0 0;
  width: 100%;
  display: flex;
  justify-content: center;
}

.detail_r .el-input--medium {
  margin: 0 10px;
}

/* .el-input--medium {
    width: 160px !important;
  } */
.upload-demo {
  width: 400px !important;
}

.listBox {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px 0px;
}

.listBox_head {
  margin-bottom: 20px;
  display: flex;
}

.dis_play {
  display: flex;
  align-items: center;
}
</style>
